package com.xishu.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.xishu.config.Config;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class OssService {
    private static Logger logger = LoggerFactory.getLogger(OssService.class);

    private static OssService ourInstance = new OssService();

    public static OssService getInstance() {
        return ourInstance;
    }

    private OssService() {
    }


    /**
     * 上传对象
     *
     * @param bucketName
     * @param objectName
     * @param srcFile
     */
    public void uploadObject(String bucketName, String objectName, File srcFile) {
        logger.info("will upload file {} to bucket {} object {}", srcFile.getAbsolutePath(), bucketName, objectName);
        OSSClient ossClient = OSSClientFactory.getInstance().createClient();
        ossClient.putObject(bucketName, objectName, srcFile);
        logger.info("upload file {} done", srcFile.getAbsolutePath());
    }

    /**
     * 上传文件到桶
     *
     * @param srcFile
     */
    public void uploadObject(File srcFile) {
        Config config = Config.getInstance();
        uploadObject(config.getPublicBucketName(), srcFile.getName(), srcFile);
    }

    /**
     * 下载文件
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    public File downloadFile(String bucketName, String objectName) throws Throwable {
        logger.info("will download  bucket {} object {}", bucketName, objectName);
        OSSClient client = OSSClientFactory.getInstance().createClient();
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);

        File downloadFile = MongoId.getInstance().generateTmpFile(FileUtil.getSuffix(objectName));
        client.getObject(getObjectRequest, downloadFile);

        return downloadFile;
    }

}
